# 导入socket
import socket
# 导入正则表达式
import re


def send_error(tcp_clinet_socket):
    # 否则返回一个没有找到页面
    response = "HTTP/1.1 404 NOT FOUND\r\n"
    response += "\r\n"
    response += "没有找到该页面"
    tcp_clinet_socket.send(response.encode("gbk"))  # 先发送头部


# 解析数据并返回
def recv_data(tcp_clinet_socket):
    request_data = tcp_clinet_socket.recv(1024).decode("utf-8")
    # 解析数据并返回/index.html,格式GET /index.html HTTP/1.1
    str_lines = request_data.splitlines()
    if len(str_lines) == 0:
        send_error(tcp_clinet_socket)  # 发送错误数据

    print(str_lines)
    # ret = re.match("[^/]+ (/[\w]+.[\w]+) ", str_lines[0])
    ret = re.match("[^/]+(/[^ ]+)", str_lines[0])
    if ret:
        file_name = ret.group(1)  # index.html
        if file_name == "/":
            file_name = "/index.html"

        local_file_name = "." + file_name
        response = "HTTP/1.1 200 OK\r\n"
        response += "\r\n"
        try:
            f = open(local_file_name, "rb")
        except:
            send_error(tcp_clinet_socket)  # 发送错误数据
        else:
            # 发送数据给客户端
            tcp_clinet_socket.send(response.encode("utf-8"))  # 先发送头部
            # 在发送body
            return_data = f.read()
            tcp_clinet_socket.send(return_data)
    else:
        send_error(tcp_clinet_socket)  # 发送错误数据
    # 关闭的只是子进程socket
    tcp_clinet_socket.close()


def main():
    # 1.创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 允许服务端立即使用上次绑定的端口（port）
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # 2.绑定端口
    tcp_server_socket.bind(("", 9999))
    # 3.监听客户端
    tcp_server_socket.listen(128)
    while True:
        # 4.等待客户端链接
        tcp_clinet_socket, addr_socket = tcp_server_socket.accept()
        # 5.接收客户端数据
        recv_data(tcp_clinet_socket)
    tcp_server_socket.close()


if __name__ == "__main__":
    main()

